<template>
  <el-card class="chart-card">
    <div class="chart-title">{{ title }}</div>
    <v-chart class="chart" :option="chartOption" />
  </el-card>
</template>

<script setup>
import { defineProps, computed } from 'vue'
import VChart from 'vue-echarts'

const props = defineProps({
  chartData: {
    type: Array,
    required: true,
  },
  chartType: {
    type: String,
    default: 'pie',
    validator: (v) => ['pie', 'bar', 'line'].includes(v),
  },
  xField: {
    type: String,
    default: 'name',
  },
  yField: {
    type: String,
    default: 'value',
  },
  title: {
    type: String,
    required: true,
  },
})

const chartOption = computed(() => {
  const series = {
    type: props.chartType,
    data: props.chartData.map((item) => ({
      name: item[props.xField],
      value: item[props.yField],
    })),
  }

  if (props.chartType === 'pie') {
    series.radius = '50%'
    series.type = 'pie'
  }

  return {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      show: props.chartType === 'pie',
      orient: 'vertical',
      left: 'right',
    },
    xAxis:
      props.chartType !== 'pie'
        ? { type: 'category', data: props.chartData.map((i) => i[props.xField]) }
        : undefined,
    yAxis: props.chartType !== 'pie' ? {} : undefined,
    series: [series],
  }
})
</script>

<style scoped>
.chart-card {
  margin: 20px;
}
.chart {
  height: 300px;
}
.chart-title {
  font-size: 18px;
  margin-bottom: 10px;
}
</style>
